package org.stvd.common.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.stvd.common.ServiceConsts;
import org.stvd.core.util.StringUtil;

/**
 * 邮件工具类
 * @author houzx
 */
public class MailUtil {

    /** 发件邮箱服务器 */
    private String emailHost;
    /** 发件人邮箱 */
    private String emailFrom;
    /** 发件人用户名 */
    private String emailUserName;
    /** 发件人密码 */
    private String emailPassword;
    /** 收件人邮箱，多个邮箱以“;”分隔 */
    private String toEmails;
    /** 邮件主题 */
    private String subject;
    /** 邮件内容 */
    private String content;
    /** 邮件中的图片，为空时无图片。map中的key为图片ID，value为图片地址 */
    private Map<String, String> pictures;
    /** 邮件中的附件，为空时无附件。map中的key为附件ID，value为附件地址 */
    private Map<String, String> attachments;

    public String getEmailHost() {
        if (StringUtil.isEmpty(emailHost)) {
            emailHost = ServiceConsts.emailHost;
        }
        return emailHost;
    }
    public void setEmailHost(String emailHost) {
        this.emailHost = emailHost;
    }

    public String getEmailFrom() {
        if (StringUtil.isEmpty(emailFrom)) {
            emailFrom = ServiceConsts.emailFrom;
        }
        return emailFrom;
    }
    public void setEmailFrom(String emailFrom) {
        this.emailFrom = emailFrom;
    }

    public String getEmailUserName() {
        if (StringUtil.isEmpty(emailUserName)) {
            emailUserName = ServiceConsts.emailUsername;
        }
        return emailUserName;
    }
    public void setEmailUserName(String emailUserName) {
        this.emailUserName = emailUserName;
    }

    public String getEmailPassword() {
        if (StringUtil.isEmpty(emailPassword)) {
            emailPassword = ServiceConsts.emailPassword;
        }
        return emailPassword;
    }
    public void setEmailPassword(String emailPassword) {
        this.emailPassword = emailPassword;
    }

    public String getToEmails() {
        if (StringUtil.isEmpty(toEmails)) {
            return "";
        } else {
            return toEmails.trim();
        }
    }
    public void setToEmails(String toEmails) {
        this.toEmails = toEmails;
    }

    public String getSubject() {
        if (StringUtil.isEmpty(subject)) {
            return "无主题";
        } else {
            return subject.trim();
        }
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        if (StringUtil.isEmpty(content)) {
            return "";
        } else {
            return content.trim();
        }
    }
    public void setContent(String content) {
        this.content = content;
    }

    public Map<String, String> getPictures() {
        return pictures;
    }
    public void setPictures(Map<String, String> pictures) {
        this.pictures = pictures;
    }

    public Map<String, String> getAttachments() {
        return attachments;
    }
    public void setAttachments(Map<String, String> attachments) {
        this.attachments = attachments;
    }

    /**
     * 发送邮件
     * 
     * @author geloin
     * @date 2012-5-9 上午11:18:21
     * @throws Exception
     */
    public void sendEmail() {
        if (this.getEmailHost().equals("")
                || this.getEmailFrom().equals("")
                || this.getEmailUserName().equals("")
                || this.getEmailPassword().equals("")) {
            throw new RuntimeException("发件人信息不完全，请确认发件人信息！");
        }

        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        // 设定mail server
        senderImpl.setHost(emailHost);

        // 建立邮件消息
        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = null;
        try {
            messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println(e);
        }

        // 设置发件人邮箱
        try {
            messageHelper.setFrom(emailFrom);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println(e);
        }

        // 设置收件人邮箱
        String[] toEmailArray = toEmails.split(";");
        List<String> toEmailList = new ArrayList<String>();
        if (null==toEmailArray || toEmailArray.length<=0) {
            throw new RuntimeException("收件人邮箱不得为空！");
        } else {
            for (String s : toEmailArray) {
                if (!StringUtil.isEmpty(s)) {
                    toEmailList.add(s);
                }
            }
            if (null==toEmailList || toEmailList.size()<=0) {
                throw new RuntimeException("收件人邮箱不得为空！");
            } else {
                toEmailArray = new String[toEmailList.size()];
                for (int i = 0; i < toEmailList.size(); i++) {
                    toEmailArray[i] = toEmailList.get(i);
                }
            }
        }
        try {
            messageHelper.setTo(toEmailArray);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println(e);
        }

        // 邮件主题
        try {
            messageHelper.setSubject(subject);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println(e);
        }

        // true 表示启动HTML格式的邮件
        try {
            messageHelper.setText(content, true);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println(e);
        }

        // 添加图片
        if (null != pictures) {
            for (Iterator<Map.Entry<String, String>> it=pictures.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry<String, String> entry = it.next();
                String cid = entry.getKey();
                String filePath = entry.getValue();
                if (null == cid || null == filePath) {
                    throw new RuntimeException("请确认每张图片的ID和图片地址是否齐全！");
                }

                File file = new File(filePath);
                if (!file.exists()) {
                    throw new RuntimeException("图片" + filePath + "不存在！");
                }

                FileSystemResource img = new FileSystemResource(file);
                try {
                    messageHelper.addInline(cid, img);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
            }
        }

        // 添加附件
        if (null != attachments) {
            for (Iterator<Map.Entry<String, String>> it=attachments.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry<String, String> entry = it.next();
                String cid = entry.getKey();
                String filePath = entry.getValue();
                if (null == cid || null == filePath) {
                    throw new RuntimeException("请确认每个附件的ID和地址是否齐全！");
                }

                File file = new File(filePath);
                if (!file.exists()) {
                    throw new RuntimeException("附件" + filePath + "不存在！");
                }

                FileSystemResource fileResource = new FileSystemResource(file);
                try {
                    messageHelper.addAttachment(cid, fileResource);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    System.out.println(e);
                }
            }
        }

        Properties prop = new Properties();
        prop.put("mail.smtp.auth", "true"); // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
        prop.put("mail.smtp.timeout", "25000");
        // 添加验证
        MailAuthenticator auth = new MailAuthenticator(emailUserName, emailPassword);
        Session session = Session.getDefaultInstance(prop, auth);
        senderImpl.setSession(session);

        // 发送邮件
        senderImpl.send(mailMessage);
    }

    /**
     * 验证邮箱格式是否正确
     * @param email
     * @return
     */
    public boolean validateEmail(String email) {
        try {
            // Create InternetAddress object and validated the email address.
            InternetAddress internetAddress = new InternetAddress(email);
            internetAddress.validate();
            return true;
        } catch (AddressException e) {
            e.printStackTrace();
        }
        return false;
    }
}
